package com.zhss.demo.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.lang.reflect.Field;

public class LeaderLatchDemo {
    public static void main(String[] args) throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(
                1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(
                "localhost:2181",
                5000,
                3000,
                retryPolicy);
        client.start();
        LeaderLatch leaderLatch = new LeaderLatch(client, "/leader/latch");
        leaderLatch.start();
        leaderLatch.await(); // 直到等待他成为leader再往后走
        Boolean hasLeaderShip = leaderLatch.hasLeadership();
        System.out.println(Thread.currentThread().getName() + " 是否成为leader：" + hasLeaderShip);
        System.out.println(Thread.currentThread().getName() + " 临时节点path：" + getFieldValue(leaderLatch, "ourPath"));
//        throw new RuntimeException();
        Thread.sleep(5000);
        leaderLatch.close();
        Thread.sleep(Integer.MAX_VALUE);
    }
    public static Object getFieldValue(Object object, String field) throws Exception {
        Class<?> aClass = object.getClass();
        Field declaredField = aClass.getDeclaredField(field);
        declaredField.setAccessible(true);
        return declaredField.get(object);
    }
}

